<?php

class AuthController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('auth/loggedout');
    }

    public function loginAction()
    {
        if(Zend_Auth::getInstance()->hasIdentity())
        {
           $this->_redirect('index/index');
        }

        $loginForm=new Application_Form_LoginForm();

        $request=$this->getRequest();
        if($request->isPost())
        {
           if($loginForm->isValid($this->_request->getPost()))
           {
              $authAdapter=$this->  getAuthAdapter();

              $username=$loginForm->getValue('username');
              $password=$loginForm->getValue('password');

              $authAdapter -> setIdentity($username)
                           -> setCredential($password);

              $auth=Zend_Auth::getInstance();
              $result=$auth->  authenticate($authAdapter);

              if($result->  isValid())
              {
                 $identity=$authAdapter->  getResultRowObject();

                 $identityStorage=$auth->  getStorage();
                 $identityStorage -> write($identity);

                 $this->  _redirect('index/index');
              }
              else
              {
                 $message="Invalid username/password";
                 $this->view->errMessage=$message;
              }
           }
        }

        $this->view->form=$loginForm;
    }

    public function loggedoutAction()
    {
        // action body
    }

    private function getAuthAdapter()
    {
       $authAdapter=new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
       $authAdapter -> setTableName('users')
                    -> setIdentityColumn('username')
                    -> setCredentialColumn('password')
                    -> setCredentialTreatment('MD5(?)');
       return $authAdapter;
    }

}













